<template>
  <div class='content-body'>
    <el-card>
      <el-tabs v-model="state.activeName" @tab-click="handleClick($event)">
        <el-tab-pane label='JSON解析' name="JsonFormat">
          <div>
            <el-row style="margin-left:40px; margin-bottom: 20px">
              <el-button type="primary" @click="formatJson">格式化</el-button>
              <el-button type="primary" @click="compressJson">压缩</el-button>
              <el-button type="primary" @click="escapeJson" round>转义</el-button>
              <el-button type="primary" @click="unescapeJson" round>去除转义</el-button>
              <el-button type="primary" @click="copyJson" round>复制结果</el-button>
              <el-button type="danger" @click="clearData" round>清空数据</el-button>
              <el-input v-model='state.extractDataParam.JsonPathExpression' clearable class="expression-input"
                        placeholder='请输入JsonPath表达式'>
              </el-input>
              <el-button type="primary" @click="extractData" class="button-class" :loading='state.buttonStart' round>
                提取数据
              </el-button>
              <el-dialog
                  :title="state.extractDataParam.title"
                  v-model:visible="state.dialogVisible"
                  :lock-scroll="true"
                  class="global-el-dialog"
                  :before-close="handleClose">
                <span>{{ state.extractDataParam.extractDataResult }}</span>
                <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="copyJson">复制结果</el-button>
              </span>
              </el-dialog>
            </el-row>
          </div>
          <div>
            <z-monaco-editor v-if="state.tabsArr.JsonFormat" v-model:value="state.jsonCode"></z-monaco-editor>
          </div>
        </el-tab-pane>
        <el-tab-pane label='文本对比' name="TextDiff">
          <div>
            <z-monaco-editor v-if="state.tabsArr.TextDiff" :is-diff='true' v-model:old-string="state.oldString"
                             v-model:new-string="state.newString"></z-monaco-editor>
          </div>
        </el-tab-pane>
        <el-tab-pane label='时间戳转换' name="TimestampConversion">
          <div>
            <TimestampConversion v-if="state.tabsArr.TimestampConversion"></TimestampConversion>
          </div>
        </el-tab-pane>
        <!--      <el-tab-pane label='Cron表达式' name="VueCron">-->
        <!--        <vueCronTab v-if="tabsArr.VueCron"></vueCronTab>-->
        <!--      </el-tab-pane>-->
        <!--      <el-tab-pane label='JsonToExcel' name="JsonToExcel">-->
        <!--        <DynamicTableView v-if="tabsArr.JsonToExcel"></DynamicTableView>-->
        <!--      </el-tab-pane>-->
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup name="CommonTools">
import query from 'json-query'
import {reactive} from "vue";
// import TimestampConversion from "/@/views/common/tools/";
// import vueCronTab from "@/components/VueCron/index.vue";
// import DynamicTableView from "@/views/uap/common/jsonToExcel/DynamicTableView.vue";

const state = reactive({
  activeName: "JsonFormat",
  tabsArr: {
    JsonFormat: true,
    TextDiff: true,
    DataExtract: false,
    TimestampConversion: false,
    VueCron: false,
    JsonToExcel: false,
  },
  jsonCode: '[{"name":"张三","age":18},{"name":"李四","age":19}]',
  jsonData: '',
  compressedJson: '',
  extractResultData: '',
  JsonFormatValue: '{"name":"张三","age":18}',
  extractDataParam: {
    title: '',
    extractDataResult: null,
    JsonPathExpression: '$..name',
  },
  dialogVisible: false,

  // 文本对比
  oldString: '',
  newString: '',
  tableKey: 0,
  listLoading: true,
  list: null,
  total: 0,
  buttonStart: false,
  jsonString: '',
  jsonFormat: {
    jsonData: {test: 1}
  },
  // 数据提取
  rules: {
    jsonData: [{required: true, message: '请输入JSON数据', trigger: 'blur'}],
    expr: [{required: true, message: '请输入JSONPATH表达式', trigger: 'blur'}],
  },
  // vueCronTab
  input: "",
  cronExpression: "",
  showCron: false,
  expression: '',
  hideComponent: ["second"],
})
const empty = (val) => {
  switch (val) {
    case "":
    case null:
    case false:
    case undefined:
      return true
    default:
      return false
  }
}

const handleClick = (tab) => {
  // tabs的切换点击方法，tab中的name是当前点击选中的哪一项的name值
  for (const key in state.tabsArr) {
    state.tabsArr[key] = tab.props.name === key;
    console.log('當前tab：', state.tabsArr[key], tab.props.name, key)
  }
}

const formatJson = () => {
  //格式化JSON
  console.log('--', state.jsonCode)
  try {
    state.jsonCode = JSON.stringify(
        JSON.parse(state.jsonCode),
        null,
        2//用于缩进的空格数
    );
  } catch (error) {
    console.error('无法格式化JSON数据：' + error);
  }
}


//转义JSON数据
const escapeJson = () => {
  try {
    console.log(state.jsonCode)
    state.jsonCode = state.jsonCode.replace(/"/g, '\\"')
    console.log(state.jsonCode)
  } catch (error) {
    console.error('无法转义JSON数据：' + error);
  }
}
//去除转义
const unescapeJson = () => {
  try {
    state.jsonCode = state.jsonCode.replace(/\\"/g, '"')
  } catch (error) {
    console.error('无法去除转义JSON数据：' + error);
  }
}

//复制数据
const copyJson = () => {
  console.log('当前tab:', state.activeName, 'dialogVisible值:', state.dialogVisible)
  if (state.activeName === 'JsonFormat' && state.dialogVisible === false) {
    navigator.clipboard.writeText(state.jsonCode)
    state.$message.success('复制成功')
  } else if (state.activeName === 'DataExtract') {
    navigator.clipboard.writeText(state.extractResultData)
    state.$message.success('复制成功')
  } else if (state.activeName === 'JsonFormat' && state.dialogVisible === true) {
    console.log('复制的数据：', state.extractDataParam.extractDataResult)
    navigator.clipboard.writeText(JSON.stringify(state.extractDataParam.extractDataResult))
    state.dialogVisible = false
    state.$message.success('复制成功')
  } else {
    state.$message.error('复制失败')

  }
}
//压缩SON
const compressJson = () => {
  try {
    const parsedData = JSON.parse(this.jsonCode)
    this.jsonCode = JSON.stringify(parsedData)
  } catch (error) {
    console.error('无法压缩JSON数据：' + error)
  }
}

// 提取数据前端处理
const extractData = () => {
  try {
    // 提取数据后打开弹窗
    console.log('数据：', state.jsonCode, '表达式：', state.extractDataParam.JsonPathExpression)
    if (state.empty(state.jsonCode) || state.empty(state.extractDataParam.JsonPathExpression)) {
      state.$message.error('请输入JSON表达式和JSON数据')
    } else {
      const jsonObject = JSON.parse(state.jsonCode);
      state.extractDataParam.extractDataResult = query(jsonObject, state.extractDataParam.JsonPathExpression)
      state.extractDataParam.title = '提取数量：' + state.extractDataParam.extractDataResult.length
      state.dialogVisible = true
    }
  } catch (error) {
    console.error('无法提取数据：' + error);
  }
}

//清除数据
const clearData = () => {
  state.jsonCode = ''
}

const handleClose = (done) => {
  state.$confirm('确认关闭？')
      .then(_ => {
        done()
      }).catch(_ => {
  })
}

// vueCronTab 函数
const crontabFill = (value) => {
  //确定后回传的值
  state.input = value;
  console.log("input:", state.input)
}

const showDialog = () => {
  state.cronExpression = state.input;
  console.log("state.cronExpression:", state.cronExpression)
  state.showCron = true;
}

</script>

<style lang="scss" scoped>
.dialog-class {
  .el-dialog__body {
    max-height: calc(100vh - 500px);
    min-height: 100px;
    overflow-y: auto;
  }
}

.expression-input {
  width: 200px;
  margin-left: 10px;
}

.button-class {
  margin-left: 10px;
  vertical-align: bottom;
}

.text-color {
  color: red;
  margin-left: 30px;
}

.el-button--primary {
  //background-color: #1D6FA3;
  border-radius: 5px;
  color: #ffffff;
}

.input-class {
  width: 35%;
  font-size: 20px;
  color: #1D6FA3;

  .el-input__inner {
    height: 50px;
  }
}
</style>